<template>
  <!-- 二级路由页面容器（右下角） -->
  <div class="departments-container">
    <div class="app-container">
      <!-- 卡片组件(分为头部和身体) -->
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <!-- tabs标签页导航 -->
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="组织架构" name="first" class="tab-pane">
              <!-- 头部 -->
              <el-row type="flex" justify="space-between" align="middle" class="department-header">
                <!-- 第一列20份 -->
                <el-col :span="20">
                  <i class="el-icon-s-home" />
                  <span class="company">广西教育科技股份有限公司</span>
                </el-col>
                <!-- 第二列4份 -->
                <el-col :span="4">
                  <!-- 在容器范围里, 一行再分2列 -->
                  <el-row type="flex" justify="end">
                    <el-col>负责人</el-col>
                    <el-col>
                      <!-- 这个之前在头部导航右侧下拉菜单讲过 -->
                      <el-dropdown>
                        <!-- 下拉菜单文字 -->
                        <span class="el-dropdown-link">
                          操作<i class="el-icon-arrow-down el-icon--right" />
                        </span>
                        <!-- 下拉项 -->
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item @click.native="add(data)">添加子部门</el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <!--tree
              props是tree的配置项
               -->
              <el-tree class="departments-tree" :data="treeData" :props="defaultProps" :default-expand-all="true">
                <!-- 默认插槽  并且使用内部的数据进行自定义模板的渲染, scope.data 所以直接key解构赋值变量也是data(对应数据对象)-->
                <!-- #default ="{data}" 写全了 v-slot:default = "scope" v-slot:可以简化成#-->
                <!-- <template v-slot:default=" scope ">  下面取值scope.data.name-->
                <!-- 具名插槽default可以分配给内slot标签无名的/有default名字的都可以分配 -->
                <template #default="{ data }">
                  <el-row
                    type="flex"
                    justify="space-between"
                    align="middle"
                    style="height: 40px; width: 100%;"
                  >
                    <!-- 部门名字 -->
                    <el-col :span="20">
                      <span>{{ data.name }}</span>
                    </el-col>
                    <!-- 功能操作区域 -->
                    <el-col :span="4">
                      <el-row type="flex" justify="end">
                        <!-- 两个内容 -->
                        <el-col>{{ data.manager }}</el-col>
                        <el-col>
                          <!-- 下拉菜单 element -->
                          <el-dropdown>
                            <span> 操作<i class="el-icon-arrow-down" /> </span>
                            <!-- 下拉菜单 -->
                            <el-dropdown-menu slot="dropdown">
                              <el-dropdown-item @click.native="add(data)">添加子部门</el-dropdown-item>
                              <el-dropdown-item @click.native="edit(data)">编辑部门</el-dropdown-item>
                              <el-dropdown-item v-if="data && !data.children" @click.native="del(data)">删除部门</el-dropdown-item>
                            </el-dropdown-menu>
                          </el-dropdown>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-row>
                </template>
              </el-tree>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-card>
      <!-- 添加子部门弹窗 -->
      <depart-dialog
        ref="departDialog"
        :origin-list="originList"
        :click-depart-id="clickDepartId"
        :dialog-visible.sync="dialogVisible"
        :is-edit="isEdit"
        :employees-simple-list="employeesSimpleList"
        @addDepartEV="addDepartFn"
      />
    </div>
  </div>
</template>

<script>
import { getDepartmentsListAPI, getEmployeesSimpleListAPI, addDepartmentAPI, getDepartDetailAPI, updateDepartmentsAPI, delDepartmentAPI } from '@/api'
import { transTree } from '@/utils/index'
import departDialog from './components/departDialog.vue'
export default {
  name: 'Departments',
  components: { departDialog },
  data() {
    return {
      activeName: 'first',
      treeData: [{
        departName: '总裁办',
        name: '孙财'
      },
      {
        departName: '行政部',
        name: '罗晓晓'
      },
      {
        departName: '人事部',
        name: '安小晴',
        children: [
          {
            departName: '财务核算部'
          }
        ]
      },
      {
        departName: '财务部',
        name: '',
        children: [
          {
            departName: '财务核算部'
          },
          {
            departName: '税务管理部'
          },
          {
            departName: '薪资管理部'
          }
        ]
      },
      {
        departName: '技术部',
        name: '',
        children: [
          {
            departName: '前端技术部'
          },
          {
            departName: '后端技术部'
          }
        ]
      },
      {
        departName: '运营部',
        name: ''
      },
      {
        departName: '市场部',
        name: '武高丽',
        children: [
          {
            departName: '市场部1'
          },
          {
            departName: '市场部2'
          }
        ]
      }],
      defaultProps: {
        children: 'children',
        label: 'departName'
      },
      dialogVisible: false, // 控制添加子部门dialog出现或隐藏
      employeesSimpleList: [], // 员工简单列表
      isEdit: false,
      clickDepartId: '', // 点击那行部门的id
      originList: [] // 用于校验部门列表扁平数组
    }
  },
  created() {
    this.getDepartmentsListFn()
    this.getEmployeesSimpleListFn()
  },
  methods: {
    // 获取部门列表
    async getDepartmentsListFn() {
      const res = await getDepartmentsListAPI()
      // 把扁平的数组里的对象，映射一份只有关键四对key+value值对象，形成一个新数组
      this.originList = res.data.depts.map(item => (
        {
          id: item.id,
          code: item.code,
          name: item.name,
          pid: item.pid
        }
      ))
      this.treeData = transTree(res.data.depts, '')
      console.log(this.treeData)
    },
    // 获取员工简单列表
    async getEmployeesSimpleListFn() {
      const res = await getEmployeesSimpleListAPI()
      console.log(res)
      // console.log(1)
      this.employeesSimpleList = res.data.rows
      // console.log(this.employeesSimpleList)
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    handleNodeClick(data) {
      console.log(data)
    },
    // 正文部分-右侧的添加子部门
    // 头部-添加子部门（data -undefined）一级部门的pid=''
    // 列表-添加子部门（data是一行对应的部门对象）-treeData里的数据(子部门pid = 父id)
    add(data) {
      if (data === undefined) {
        this.clickDepartId = '' // 公司右侧的id为''
      } else {
        this.clickDepartId = data.id
      }
      // 子部门的pid= 父级id
      this.isEdit = false
      this.dialogVisible = true // 添加子部门弹窗出现
      this.clickDepartId = data.id // 点击添加子部门dialog->出现
    },
    // 编辑子部分
    async edit(data) {
      this.clickDepartId = data.id // 编辑时的id存一下
      this.isEdit = true
      this.dialogVisible = true // 弹窗出现
      const res = await getDepartDetailAPI(data.id)
      console.log(res)
      // this.$refs.departDialog->拿到departDialog的this的值（组件对象）
      this.$refs.departDialog.form = res.data
    },
    // 右侧 - 删除部门
    async del(data) {
      // 显示删除确认消息对话框
      const delRes = await this.$confirm('此操作将永久删除部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果返回的结果是 cancel 说明用户取消了删除
      if (delRes === 'cancel') return this.$message('您取消了删除')
      // 调用删除接口
      const delDepartRes = await delDepartmentAPI(data.id)
      // 根据状态值, 查看是否删除成功
      if (!delDepartRes.success) return this.$message.error(delDepartRes.message)
      // 删除成功需要给用户进行提示
      this.$message.success(delDepartRes.message)
      // 删除后需要重新获取当前页面数据
      this.getDepartmentsListFn()
    },
    // 添加子部门事件
    async addDepartFn(formObj) {
      formObj.pid = this.clickDepartId
      const res = await addDepartmentAPI(formObj)
      console.log(res)
      // await成功才往下走，下面默认成功
      // 刷新列表
      this.getDepartmentsListFn()
    },
    // 新增-添加部门的方法
    async addDepartmentsFn(dataObj) {
      if (this.isEdit) { // 编辑状态
        dataObj.id = this.clickDepartId
        const res = await updateDepartmentsAPI(dataObj)
        console.log(res)
      } else { // 新增状态
        dataObj.pid = this.clickDepartId
        const res = await addDepartmentAPI(dataObj)
        console.log(res)
      }
      this.getDepartMentsListFn()
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  padding: 10px 30px;
}

.tab-pane {
  padding: 20px 80px;

  .company {
    margin-left: 12px;
    font-weight: bold;
    font-size: 14px;
  }

  .department-header {
    height: 50px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ccc;
  }
}
.departments-tree {
  margin: 12px 0px;
}
</style>
